﻿using System;
using System.Text;
using System.Globalization;

using gKodes.IO;

namespace gKodes.Windows.Forms
{
    public class ASCIIEncoding : IDEncoder
    {
        private byte[] tBytes = new byte[1];

        public DataSizes DataSize
        {
            get { return DataSizes.Octet; }
        }

        public string Encode(IDataSource data, int index)
        {
            this.tBytes[0] = data[index];
            if (this.Filter((char)this.tBytes[0]))
                return Encoding.ASCII.GetString(this.tBytes);
            return ".";
        }

        public bool Filter(char c)
        {
            switch (char.GetUnicodeCategory(c))
            {
                case UnicodeCategory.Control:
                case UnicodeCategory.Surrogate:
                case UnicodeCategory.SpaceSeparator:
                case UnicodeCategory.LineSeparator:
                case UnicodeCategory.ParagraphSeparator:
                case UnicodeCategory.ModifierSymbol:
                case UnicodeCategory.OtherSymbol:
                case UnicodeCategory.OtherNumber:
                    return false;
                case UnicodeCategory.OtherPunctuation:
                    return !(c > (char)0xBE);//BF
                case UnicodeCategory.LowercaseLetter:
                    return !(c > (char)0x7A);
                case UnicodeCategory.UppercaseLetter:
                    return !(c > (char)0x5A);
                default:
                    return true;
            }
        }
    }
}
